/*
 * COPYRIGHT. ShenZhen JiMi Technology Co., Ltd. 2017.
 * ALL RIGHTS RESERVED.
 *
 * No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
 * on any form or by any means, electronic, mechanical, photocopying, recording, 
 * or otherwise, without the prior written permission of ShenZhen JiMi Network Technology Co., Ltd.
 *
 * Amendment History:
 * 
 * Date                   By              Description
 * -------------------    -----------     -------------------------------------------
 * 2017年4月21日    li.shangzhi         Create the class
 * http://www.jimilab.com/
 */

package com.jimi.gateway.filter.error;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.jimi.gateway.utils.Constants;
import com.jimi.gateway.utils.ResultModel;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

/**
 * @FileName ZuulErrorFilter.java
 * @Description: zuul过滤器链发生异常统一处理
 *
 * @Date 2017年4月21日 下午4:52:17
 * @author li.shangzhi
 * @version 1.0
 */
public class ErrorFilter extends ZuulFilter {

	private static final int FILTER_ORDER = 0;

	private final Logger logger = LoggerFactory.getLogger(ErrorFilter.class);

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		logger.error("系统异常，执行的过滤器链为：{}", ctx.getFilterExecutionSummary());
		ZuulException zuulException = (ZuulException) ctx.getThrowable();
		logger.error("系统异常，发送异常的过滤器为：{}", zuulException.errorCause, zuulException.getCause());
		ctx.setResponseStatusCode(500);// 异常

		ResultModel resultModel = new ResultModel();
		resultModel.setCode(zuulException.nStatusCode);
		resultModel.setMessage(zuulException.getMessage());
		ctx.setResponseBody(JSONObject.toJSONString(resultModel));
		return null;
	}

	@Override
	public String filterType() {
		return Constants.ERROR_FILTER;
	}

	@Override
	public int filterOrder() {
		return FILTER_ORDER;
	}

}
